//
//  TaskEditingViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 2/23/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "TaskEditingViewController.h"
#import "TaskDetailViewController.h"

@interface TaskEditingViewController ()

@end

@implementation TaskEditingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    // Set the title to the user-visible name of the field.
	self.title = _editedPropertyDisplayName;
    self.view.backgroundColor = [UIColor whiteColor];
	
	// Configure the save and cancel buttons.
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
	self.navigationItem.leftBarButtonItem = cancelButton;
    
    // datepicker widget
    CGRect frame = CGRectMake(0.0, 20.0, 320.0, 400.0);
    _datePicker = [[UIDatePicker alloc] initWithFrame:frame];
    [self.view addSubview:_datePicker];
    
}

- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
    
	// Update user interface according to state.
    if ([_editedPropertyDisplayName isEqualToString:@"Start Time"]) {
        if(_startTime != NULL)
            [_datePicker setDate:_startTime animated:YES];
    }
	else {
        if(_endTime != NULL)
            [_datePicker setDate:_endTime animated:YES];
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (IBAction)save {
	
    
    // update the current value in the databbase, then return to the previous view
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"%@",[dateformatter stringFromDate:[_datePicker date]]);
    
    
    // update field
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSLog(@"database path: %@",_databasePath);
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            NSString *update_sql;
            
            if([_editedPropertyDisplayName isEqualToString:@"Start Time"])
            {
                update_sql = [NSString stringWithFormat:@"update tasklog set start_time = '%@' where id like '%@'",[dateformatter stringFromDate:[_datePicker date]],_taskID];
            } else {
                update_sql = [NSString stringWithFormat:@"update tasklog set end_time = '%@' where id like '%@'",[dateformatter stringFromDate:[_datePicker date]],_taskID];
            }
            
            const char *update_const = [update_sql UTF8String];
            sqlite3_stmt *res_update;
            if(sqlite3_prepare(_database, update_const, -1, &res_update, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",update_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                NSLog(@"query: %s",update_const);
                if(SQLITE_DONE != sqlite3_step(res_update))
                    NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(_database));
                
                sqlite3_finalize(res_update);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivityEditingViewController");
        }
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
    
    [self.navigationController popViewControllerAnimated:YES];
     
}


- (IBAction)cancel {
    // return to the previous view, without saving
    [self.navigationController popViewControllerAnimated:YES];
}



@end
